<?php session_start(); ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?php
if (isset($_SESSION['lang']))
    require_once "./language_files/editInfo_" . $_SESSION['lang'] . ".php";
else
    require_once "./language_files/editInfo_en.php";
?>
<html>
    <head>
        <title><?php echo $lang['edit']; ?></title>
        <link href="style3.css" rel="stylesheet" type="text/css" />
        <?php include 'jquery.php'; ?>
        <script type="text/javascript" src="functions.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                check_top();

            $("#removeP").click(function(){
               id = $(this).attr("memberID");
               $.ajax ({
                    type: 'POST',
                    url:  'removeProfilePic.php',
                    success: function(response) {
                        top.location.reload();
                        success("Profile picture removed successfully");
                    }
                });
            });
        });
        </script>
        <script type="text/javascript">
            function success(text) {
                document.getElementById("label2").style.color = "green"
                document.getElementById("label2").innerHTML= text;
            }
            function error(text) {
                document.getElementById("label2").style.color = "red"
                document.getElementById("label2").innerHTML= text;
            }
        </script>
    </head>
    <body>
        <?php
        include "functions.php";
        $memberID = $_SESSION['member_id'];
        echo "<h1>" . $lang['edit'] . "</h1>";
        $image_path = mysql_query("SELECT profilepic_path FROM member WHERE
                            member_id = $memberID") or die(mysql_error());
        while ($row = mysql_fetch_assoc($image_path)) {
            $image = $row['profilepic_path'];
            if($image == "./profile_pictures/default_profilepic.jpg") {
                echo "<script type='text/javascript'>
                   $(document).ready(function(){
                   $('#removeP').attr('disabled', true);
                   $('#removeP').addClass('disabledButton');
                });
                  </script>";
            } 
            echo "<table id='12' class='ediftinfo'><td colspan='10'> <div class='float_left'>
                        <img src='{$image}' alt='profile picture' width='200' height='290'/>";
        }
        ?>
        <form id="newad" name="newad" method="post" enctype="multipart/form-data" action="">
            <table class="no_border">
                <tr><td><input type="file" name="image"></td></tr>
                <tr><td><input name="Submit" type="submit" value="Upload image">
                        <button type="button" name="removeP" id="removeP">Remove current image</button><br /> <label id="label2"></label></td></tr>
            </table>
        </form></div></td>
<form name= "form" action = "" value = "Submit" method = "Post">
    <?php
    //Author Nour Ossama
    //check if the member id was passed from the previous page
    if (isset($memberID)) {
        //save member_id in a variable $memberID
        //calling function to execute it if condition was satisfied
        EditInfo($memberID);
    }
    /*
     * function EditInfo takes member_id and returns table with all
     * info about member in textboxes to be edited
     */

    function EditInfo($member_id) {
        Global $lang;
        //turn off the warnings that alert that there is an undefined index because there are no textboxes yet
        error_reporting(E_ALL ^ E_NOTICE);
        @mysql_connect("db424304376.db.1and1.com", "dbo424304376", "2v_7z8sdi!h") or die(mysql_error());
        mysql_select_db("db424304376") or die(mysql_error());
        //if save button was not yet clicked
        //print title of the page
        /*
         * query that populates all the info of the member from the db
         */
        $get_member_info = mysql_query("SELECT *
                                    FROM member
                                    WHERE member_id = '$member_id'") or die(mysql_error());
        while ($row = mysql_fetch_assoc($get_member_info)) {
            $f_name = formatText_safe($row[first_name]);
            $l_name = formatText_safe($row[last_name]);
            $email = formatText_safe($row[email]);
            $phone = formatText_safe($row[phoneNum]);
            $fax = formatText_safe($row[fax]);
            $address = formatText_safe($row[address]);
            $affiliation = formatText_safe($row[affiliation]);
            $fb_page = formatText_safe($row[fb_page]);
            $linked_page = formatText_safe($row[linked_page]);
            $website = formatText_safe($row[website]);
            $search_gate = formatText_safe($row[research_gate_site]);
            $acdemic_site = formatText_safe($row[academic_site]);
            $mendely_site = formatText_safe($row[mendeley_site]);
            //open table
            /*
             * print First Name in a row
             * and in the column next to it print first_name from db inside the textbox
             */
            print "<fieldset><legend>Options</legend><div class'links'>
                            <a href=\"changepass.php\">Change password</a></div></fieldset>";
            echo "<tr>
         <td>" . $lang['hint'] . "</td>";
            echo "<tr>
         <td><b>" . $lang['f_name'] . "</b></td>
         <td><input type =\"text\" name =\"first_name\" value=\"$f_name\" onkeypress=\"return isLetterOnly(event)\"/></td>
         </tr>";
            /*
             * print Last Name in a row
             * and in the column next to it print last_name from db inside the textbox
             */
            echo "<tr>
        <td><b>" . $lang['l_name'] . "</b></td>
        <td><input type =\"text\" name =\"last_name\" value=\"$l_name\"onkeypress=\"return isLetterOnly(event)\"/></td>
        </tr>";
            /*
             * print Email in a row
             * and in the column next to it print email from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['email'] . "</b></td>
        <td><input type =\"email\" name =\"email\" value=\"$email\"/></td>
        </tr>";

            /*
             * print Phone Number in a row
             * and in the column next to it print phoneNum from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['phone'] . "</b></td>
        <td><input type =\"text\" name =\"phoneNum\" value=\"$phone\"onkeypress=\"return isNumberOnly(event)\"/></td>
        </tr>";

            /*
             * print Fax Number in a row
             * and in the column next to it print fax from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['fax'] . "</b></td>
        <td><input type =\"text\" name =\"fax\" value=\"$fax\"onkeypress=\"return isNumberOnly(event)\"/></td>
        </tr>";
            /*
             * print Address in a row
             * and in the column next to it print address from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['address'] . "</b></td>
        <td><input type =\"text\" name =\"address\" value=\"$address\"onkeypress=\"return alpha(event)\"/></td>
        </tr>";
            /*
             * print Affiliation in a row
             * and in the column next to it print affiliation from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['affiliation'] . "</b></td>
        <td><input type =\"text\" name =\"affiliation\" value=\"$affiliation\"onkeypress=\"return isLetterOnly(event)\"/></td>
        </tr>";
            /*
             * print Facebook Page in a row
             * and in the column next to it print fb_page from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['facebook'] . "</b></td>
        <td><input type =\"url\" name =\"fb_page\" value=\"$fb_page\"/></td>
        </tr>";
            /*
             * print LinkedIn Page in a row
             * and in the column next to it print linked_page from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['linkedPage'] . "</b></td>
        <td><input type =\"url\" name =\"linked_page\" value=\"$linked_page\"/></td>
        </tr>";
            /*
             * print Website in a row
             * and in the column next to it print website from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['website'] . "</b></td>
        <td><input type =\"url\" name =\"website\" value=\"$website\"/></td>
        </tr>";
            /*
             * print Research Gate Site in a row
             * and in the column next to it print website from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['research_gate'] . "</b></td>
        <td><input type =\"url\" name =\"research_gate_site\" value=\"$search_gate\"/></td>
        </tr>";
            /*
             * print Academic Gate Site in a row
             * and in the column next to it print academic_site from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['academic_site'] . "</b></td>
        <td><input type =\"url\" name =\"academic_site\" value=\"$acdemic_site\"/></td>
        </tr>";
            /*
             * print Mendeley Site in a row
             * and in the column next to it print mendeley_site from db inside the textbox
             */

            echo "<tr>
        <td><b>" . $lang['mendeley_site'] . "</b></td>
        <td><input type =\"url\" name =\"mendeley_site\" value=\"$mendely_site\"/></td>
        </tr>";
        }
        //close table
        //new line

        /* query that retrieves all the other emails of the
         * member from table email
         */ // maximum 5 email!!
        $get_member_other_email = mysql_query("SELECT email
                                                           FROM emails
                                                           WHERE member_id = '$member_id'") or die(mysql_error());
        /* if result set of query is not empty i.e contains some values
         * print Other Emails in a row
         */
        if (mysql_num_rows($get_member_other_email) > 0) {
            //open new table
            echo '<table width="20%" id=22>';
            echo "
                            <td colspan='10'><b>" . $lang['message_1'] . "</b></td>
                            ";
            //create counter and set it to zero
            $counter = 0;
            while ($row = mysql_fetch_assoc($get_member_other_email)) {
                //increment counter by 1
                $counter++;
                /* and in the column next to Other Emails print
                 * checkbox with the value of the email and a
                 * text box which contains email from db, the hidden field stores the counter
                 */
                echo "<tr>
                            <td>
                            <input title='delete' class='delete' id='dd' type=\"checkbox\" name=\"check_mail$counter\" value=\"$row[email]\"/></td>
                            <td><input type =\"text\" name =\"other_email$counter\" value=\"$row[email]\"/></td>
                            </tr>";

                echo "<input type=\"hidden\" name=\"check_mail\" value=\"$counter\"/>";
            }

        }
         echo "<tr><td colspan='10'><b>" . $lang['extra_email'] . "<b></td></tr><tr><td colspan='10'>

                    <label>Email 1: </label><input type='text' name='email1' id='email1' /><br />
                    <label>Email 2: </label><input type='text' name='email2' id='email2' /><br />
                    <label>Email 3: </label><input type='text' name='email3' id='email3' /><br />
                    <label>Email 4: </label><input type='text' name='email4' id='email4' /><br />
                    <label>Email 5: </label><input type='text' name='email5' id='email5' />
                    </td>
                    </tr>";
            echo "</table>";
        /*
         * printing the Add Extra Email button and then the textboxes that appear
         * each time this button is clicked
         */
        echo "<tr><td><p align='center'><input class='padding' type =\"submit\" name = \"save\" value = \"" . $lang['button_2'] . "\" /></p></td></tr>";
        //close table
        echo "</table></div>";
        //nextline
        //print the save button

        if (isset($_POST['save'])) {//if save button was clicked
            //save all the entries in the textboxes in variables
            $first_name = mysql_safe($_POST['first_name']);
            $last_name = mysql_safe($_POST['last_name']);
            $main_email = mysql_safe($_POST['email']);
            $phoneNum = mysql_safe($_POST['phoneNum']);
            $fax = mysql_safe($_POST['fax']);
            $address = mysql_safe($_POST['address']);
            $affiliation = mysql_safe($_POST['affiliation']);
            $fb_page = mysql_safe($_POST['fb_page']);
            $linked_page = mysql_safe($_POST['linked_page']);
            $website = mysql_safe($_POST['website']);
            $research_gate_site = mysql_safe($_POST['research_gate_site']);
            $academic_site = mysql_safe($_POST['academic_site']);
            $mendeley_site = mysql_safe($_POST['mendeley_site']);
            //a query that checks the user is in the table and get his info
            $check_user = mysql_query("SELECT * FROM member WHERE member_id ='$member_id'");
            if (mysql_num_rows($check_user) > 0) {
                //query that updates table member with new info from textboxes
                $update_member_info = mysql_query("UPDATE member
                                                   SET first_name = '$first_name',
                                                       last_name = '$last_name',
                                                       email = '$main_email',
                                                       phoneNum = '$phoneNum',
                                                       fax = '$fax',
                                                       address = '$address',
                                                       affiliation = '$affiliation',
                                                       fb_page = '$fb_page',
                                                       linked_page = '$linked_page',
                                                       website = '$website',
                                                       research_gate_site = '$research_gate_site',
                                                       academic_site = '$academic_site',
                                                       mendeley_site = '$mendeley_site'
                                                    WHERE member_id = '$member_id'") or die(mysql_error());
                echo "</table>";
//counter $X that loops on textboxes, their maximum should be 19
                $get_member_other_email = mysql_query("SELECT email
                                                           FROM emails
                                                           WHERE member_id = '$member_id'") or die(mysql_error());
                /* if result set of query is not empty i.e contains some values
                 * print Other Emails in a row
                 */
                if (isset($_POST['email1']) || isset($_POST['email2']) || isset($_POST['email3']) || isset($_POST['email4']) || isset($_POST['email5'])) {
                    if ($_POST['email1'] != null) {
                        $email = mysql_escape_string($_POST['email1']);
                        $q = mysql_query("INSERT INTO emails (member_id, email)
                   VALUES ($member_id, '$email')") or die(mysql_error());
                    } if ($_POST['email2'] != null) {
                        $email = mysql_escape_string($_POST['email2']);
                        $q = mysql_query("INSERT INTO emails (member_id, email)
                   VALUES ($member_id, '$email')") or die(mysql_error());
                    } if ($_POST['email3'] != null) {
                        $email = mysql_escape_string($_POST['email3']);
                        $q = mysql_query("INSERT INTO emails (member_id, email)
                   VALUES ($member_id, '$email')") or die(mysql_error());
                    } if ($_POST['email4'] != null) {
                        $email = mysql_escape_string($_POST['email4']);
                        $q = mysql_query("INSERT INTO emails (member_id, email)
                   VALUES ($member_id, '$email')") or die(mysql_error());
                    } if ($_POST['email5'] != null) {
                        $email = mysql_escape_string($_POST['email5']);
                        $q = mysql_query("INSERT INTO emails (member_id, email)
                   VALUES ($member_id, '$email')") or die(mysql_error());
                    }
                } else {
                    echo "<script>alert('mfish 8aha');</script>";
                }
                if ($get_member_other_email) {
                    //open new table
                    echo '<table width="20%" id=22>';
                    echo "<tr>
                            <td><b>Other Email(s) (Click checkboxes of emails you wish to delete)</b></td>
                            </tr>";
                    //create counter and set it to zero
                    $counter = 0;
                    while ($row = mysql_fetch_assoc($get_member_other_email)) {
                        //increment counter by 1
                        $counter++;
                        /* and in the column next to Other Emails print
                         * checkbox with the value of the email and a
                         * text box which contains email from db, the hidden field stores the counter
                         */
                        echo "<tr>
                            <td><input type=\"checkbox\" name=\"check_mail$counter\" value=\"$row[email]\">
                            <td><input type =\"text\" name =\"other_email$counter\" value=\"$row[email]\"/></td>
                            </tr>";

                        echo "<input type=\"hidden\" name=\"check_mail\" value=\"$counter\"/>";
                    }
                }

                //loop on the array of checkboxes
                for ($counter = 1; $counter <= $_POST['check_mail']; $counter++) {
                    //if the checkbox was clicked
                    if (isset($_POST["check_mail$counter"])) {
                        //save the value of the textbox in $other_email
                        $other_mail = $_POST["check_mail$counter"];
                        //a query that deletes the $other_email from table emails
                        $delete_other_email = mysql_query("DELETE FROM emails
                                                     WHERE member_id='$member_id'
                                                     AND email='$other_mail'") or die(mysql_error());
                    }
                }

                //if either of the two queries executed successfully
                if ($update_member_info || $delete_other_email) {
                    //echo heading "info saved"
                    echo "<script type='text/javascript'>
             frame = top.document.getElementById('collabsoft');
            $(frame).attr('src', 'profilePage.php?property_variable=mine&type=edit');
         </script>";
                    //load the profile page with new info and the Edit Information hyperlink
                    print "<a style=\"float:right\" href=\"editInfo.php?member_id={$member_id}\">" . $lang['edit'] . "</a>";

                    include("profilePage.php");
                } else { //if queries were not successful
                    echo ("<p>" . $lang['message_2'] .
                    mysql_error() . "</p>");
                }
            }
        }
    }
    ?>
</form>
<?php
define("MAX_SIZE", "1000");
function getExtension($str) {
    $i = strrpos($str, ".");
    if (!$i) {
        return "";
    }
    $l = strlen($str) - $i;
    $ext = substr($str, $i + 1, $l);
    return $ext;
}

$errors = 0;
if (isset($_POST['Submit'])) {
    $image = $_FILES['image']['name'];
    if ($image) {
        $filename = stripslashes($_FILES['image']['name']);
        $extension = getExtension($filename);
        $extension = strtolower($extension);
        if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
            echo '<script>error("Unknown extension!");</script>';
            $errors = 1;
        } else {
            $size = filesize($_FILES['image']['tmp_name']);
            if ($size > MAX_SIZE * 1024) {
                echo '<script>error("You have exceeded the size limit!");</script>';
                $errors = 1;
            }
            $image_name = time() . '.' . $extension;
            $newname = "./profile_pictures/" . $image_name;
            $insert = mysql_query("UPDATE member SET profilepic_path = '$newname'
        WHERE member_id = $memberID") or die(mysql_error());
            $copied = copy($_FILES['image']['tmp_name'], $newname);
            if (!$copied) {
                echo '<script>error("Copy unsuccessfull!");</script>';
                $errors = 1;
            }
        }
    } else {
        echo '<script>error("You did not choose any image!");</script>';
        $errors = 1;
    }
}
if (isset($_POST['Submit']) && !$errors) {
    echo "<script>success('File Uploaded Successfully!');
        top.location.reload();</script>";
}
mysql_close();
?>
</body>
<script type="text/javascript">

    //a function that allows only numbers and letters to be entered
    function alpha(e) {
        var k;
        document.all ? k = e.keyCode : k = e.which;
        return ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 48 && k <= 57));
    }

    //a function that allows only numbers to be entered
    function isNumberOnly(evt)
    {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57)){
            alert("Please enter numbers only.");
            return false;
        }
        return true;
    }
    //a function that allows only letters to be entered
    function isLetterOnly(evt) {
        evt = (evt) ? evt : event;
        var charCode = (evt.charCode) ? evt.charCode : ((evt.keyCode) ? evt.keyCode :
            ((evt.which) ? evt.which : 0));
        if (charCode > 31 && (charCode < 65 || charCode > 90) &&
            (charCode < 97 || charCode > 122)) {
            alert("Please enter letters only.");
            return false;
        }
        return true;
    }
</script>
</html>
